/*
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * This file is part of Harmattan SmashMiner OpenGL game application.
 * 
 * Harmattan SmashMiner OpenGL Example Application version 1.0.0
 *  
 * Latest update: 15.4.2011
 *
 * The Harmattan SmashMiner OpenGL example application demonstrates how to use 
 * the OpenGL ES in Harmattan devices.
 *
 * This example is provided as a starting point for 3rd party
 * developers (you) to ease the implementation of OpenGL based 
 * games. Ideas, parts of code or methodologies that this
 * example application uses can be freely used without restrictions.
 *
 * See file README.txt how to build and compile this example application
 * in the Harmattan SDK environment. 
 * 
 * See file INSTALL.txt to find out what is required to run this
 * application and how to install the application to the device or
 * alternatively in QEMU-emulator.
 *
 * The LICENSE.txt file explains the license this software is provided
 * with. A copy of the same license is included in this source file.
 * 
 */

/*
 * Copyright (C) 2011 by Nokia Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
\file HighScores.qml
\brief This is the high scores view of the SmashMiner game.

See the \c highScoresView at the main.qml view.

\sa main.qml
*/

import Qt 4.7

Rectangle {
    id: highScoresView

    // Signal to return main view
    signal back()

    property bool isGameOver: false
    property bool hasHighScore: false
    property int newHighScore: -1
    property string newHighScoreTime: ""

    // Vertical margins of the view area
    property int marginsVertical: height/20
    // Height of the view header
    property int headerHeight: marginsVertical*2
    // Horizontal margins of the view area
    property int marginsHorizontal: headerHeight+marginsVertical
    // Height of the buttons used at this view
    property int buttonHeight: headerHeight*0.9
    // Width of the buttons used at this view
    property int buttonWidth: buttonHeight*2.5
    // Width of the high score list columns
    property int columnWidth: (width-(3*marginsHorizontal))/5

    width: parent.width
    height: parent.height
    color: "black"
    z: -10
    visible: true

    // Called when the highScoresView visible property is changed
    onVisibleChanged: {
        if (visible == true) {
            if (hasHighScore == true)
                highScoreName.forceActiveFocus();
        }
    }

    Image {
        id: background
        anchors.fill: parent
        source: "qrc:/images/1024x512_01.jpg"
    }

    ViewHeader {
        id: highScoresHeader
        heading: qsTr("HIGH SCORES")
    }

    // The delegate for high score list header
    Component {
        id: highScoreListHeader
        Rectangle {
            id: scoreListHeader
            width: parent.width
            height: buttonHeight
            color: "black"
            Grid {
                columns: 5
                spacing: marginsVertical
                anchors { left: scoreListHeader.left; leftMargin: 10; verticalCenter: parent.verticalCenter }
                Text {
                    text: qsTr(" ")
                    width: 10
                }
                Text {
                    text: qsTr("NAME")
                    width: columnWidth
                    font { pointSize: 12; bold: true }
                    color: "lightgrey"
                }
                Text {
                    text: qsTr("SCORE")
                    width: columnWidth
                    font { pointSize: 12; bold: true }
                    color: "lightgrey"
                }
                Text {
                    text: qsTr("TIME")
                    width: columnWidth
                    font { pointSize: 12; bold: true }
                    color: "lightgrey"
                }
                Text {
                    text: qsTr("DATE")
                    width: columnWidth
                    font { pointSize: 12; bold: true }
                    color: "lightgrey"
                }
            }
        }
    }

    Rectangle {
        id: rectangleScores

        width: parent.width
        anchors { left: parent.left; right: parent.right; leftMargin: marginsHorizontal; rightMargin: marginsHorizontal;
            top: highScoresHeader.bottom; bottom: highScoresFooter.top }
        color: "black"
        border { width: 5; color: "#333333" }

        // View for the HighScoreModel
        ListView {
            id: highScoreList
            model: highScoreModel
            delegate: scoreDelegate
            header: highScoreListHeader
            focus: false
            currentIndex: -1
            anchors { top: parent.top; topMargin: marginsVertical; left: parent.left; leftMargin: marginsHorizontal/2;
                right: parent.right; rightMargin: marginsHorizontal/2; bottom: parent.bottom; bottomMargin: marginsVertical }

            // Score line delegate
            Component {
                id: scoreDelegate
                Rectangle {
                    id: wrapper
                    height: buttonHeight
                    width: rectangleScores.width-marginsHorizontal
                    // the highlighted line is blue so that the player knows where he landed in the high score list
                    color: ListView.isCurrentItem ? "blue" : "black"
                    border { width: ListView.isCurrentItem ? 2 :0; color: "blue" }

                    Grid {
                        columns: 5
                        rows:  1
                        anchors { left: wrapper.left; leftMargin: 10; verticalCenter: parent.verticalCenter }
                        spacing: marginsVertical
                        Text {
                            id: rankText
                            text: scoreRank
                            width: 10
                            color: ListView.isCurrentItem ? "black" : "lightgrey"
                            font { bold: true; pointSize: ListView.isCurrentItem ? 14 : 12 }
                        }
                        Text {
                            id: nameText
                            text: scoreName
                            width: columnWidth
                            color: ListView.isCurrentItem ? "black" : "lightgrey"
                            font { bold: ListView.isCurrentItem ? true : false; pointSize: ListView.isCurrentItem ? 14 : 12 }
                        }
                        Text {
                            id: scoreText
                            text: scoreValue
                            width: columnWidth
                            color: ListView.isCurrentItem ? "black" : "lightgrey"
                            font { bold: ListView.isCurrentItem ? true : false; pointSize: ListView.isCurrentItem ? 14 : 12 }
                        }
                        Text {
                            id: timeText
                            text: scoreTime
                            width: columnWidth
                            color: ListView.isCurrentItem ? "black" : "lightgrey"
                            font { bold: ListView.isCurrentItem ? true : false; pointSize: ListView.isCurrentItem ? 14 : 12 }
                        }
                        Text {
                            id: dateText
                            text: scoreDate
                            width: columnWidth
                            color: ListView.isCurrentItem ? "black" : "lightgrey"
                            font { bold: ListView.isCurrentItem ? true : false; pointSize: ListView.isCurrentItem ? 14 : 12 }
                        }
                    }
                }
            }
        }
    }

    //
    // Popup for entering the new high score
    //
    Rectangle {
        id: rectangleEnterNewScore
        color: "#555555"
        visible: hasHighScore ? true : false
        width:  parent.width
        height: hasHighScore ? buttonHeight*2 : 0
        border { width: 5; color: "#333333" }
        anchors { left: parent.left; right: parent.right; leftMargin: marginsHorizontal; rightMargin: marginsHorizontal; top: highScoresHeader.bottom }

        Grid {
            columns: 3
            rows: 1
            spacing: 20
            anchors { left: parent.left; right: parent.right; leftMargin: marginsHorizontal/2; rightMargin: marginsHorizontal/2; verticalCenter: parent.verticalCenter; }

            Item {
                width: parent.width*0.4
                height: buttonHeight
                Text {
                    text: qsTr("Enter your name:")
                    color:  "white"
                    font { pointSize: 14; bold: true; }
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

            Rectangle {
                id: nameInput
                color: "white"
                width: parent.width*0.3
                height: buttonHeight
                border.width: 2
                border.color: "#222222"
                TextInput {
                    id: highScoreName
                    color: "black"
                    cursorVisible: true
                    font.pointSize: 14
                    maximumLength: 14
                    anchors { left: parent.left; leftMargin: 10; right: parent.right; verticalCenter: parent.verticalCenter }

                    activeFocusOnPress: false

                    onAccepted: {
                        // this event will be triggered when the
                        // player has pressed ENTER on the keyboard.

                        rectangleEnterNewScore.playerNameEntered();
                    }

                    MouseArea {
                        anchors.fill: highScoreName

                        //onClicked: highScoreName.openSoftwareInputPanel();
                        onClicked: {
                            if (!highScoreName.activeFocus) {
                                highScoreName.forceActiveFocus();
                                highScoreName.openSoftwareInputPanel();
                            }
                            else {
                                highScoreName.focus = false;
                            }
                        }

                        onPressAndHold:  highScoreName.closeSoftwareInputPanel();
                    }
                }
            }
            // this is the OK button next to the players name in highscore screen
            Button {
                id: highScoreButton
                width: buttonWidth
                height: buttonHeight
                label: qsTr("OK")
                pressed: true

                onClicked: rectangleEnterNewScore.playerNameEntered()
            }

        }

        // Called when the player has entered the new high score
        function playerNameEntered() {
            highScoreName.closeSoftwareInputPanel();
            //highScoresView.newHighScoreIndex = gameSettings.setHighScore(highScoreName.text, newHighScore, newHighScoreTime);
            highScoreList.currentIndex = gameSettings.setHighScore(highScoreName.text, newHighScore, newHighScoreTime);
            highScoresView.hasHighScore = false;
            highScoreName.text = "";
            highScoresView.newHighScore = -1;
            highScoresView.newHighScoreTime = "";
        }
    }

    // Popup to show high score congratulation text
    Item {
        id: highScorePopup

        anchors { top: rectangleEnterNewScore.bottom; bottom: highScoresFooter.top; left: parent.left; right: parent.right
            leftMargin: marginsHorizontal; rightMargin: marginsHorizontal }

        Rectangle {
            id: highScorePopupBackground

            visible: hasHighScore ? true : false
            color: "black"
            opacity: 0.8
            anchors.fill: parent
        }

        Text {
            id: textCongratulations
            visible: hasHighScore ? true : false
            text: qsTr("Congratulations!")
            color: "white"
            anchors { top: parent.top; topMargin: buttonHeight; horizontalCenter: parent.horizontalCenter }
            font.pointSize: 32
        }

        Text {
            id: textTopFive
            text: qsTr("You made it to top 5")
            visible: hasHighScore ? true : false
            color: "white"
            anchors { top: textCongratulations.bottom; topMargin: 32; horizontalCenter: parent.horizontalCenter }
            font.pointSize: 32
        }
    }

    // Footer for the high scores view
    ViewFooter {
        id: highScoresFooter

        width: parent.width
        height: headerHeight

        onBackClicked: {

            // when we are at GameOver state
            // ("Play Again" button is displayed),
            // and the player clicks "Back" : now
            // we need to re-enable the mainview
            // "Play" button fading effect.

            if (isGameOver) {
                console.log("HIGHSCORE back button : enable mainview FadeOut effect.");
                mainview.doFadeOutEffect = true;
            }

            isGameOver = false;
            hasHighScore = false;
            highScoreList.currentIndex = -1;
            gameSettings.save();
            soundEngine.playMenuSound();
            back();
        }

        // Play again button to start a new game
        Button {
            id: playButton
            visible: isGameOver ? true : false
            width: buttonWidth
            height: buttonHeight
            anchors { left: parent.left; leftMargin: marginsHorizontal; verticalCenter: parent.verticalCenter }
            label: qsTr("Play again")
            pressed: true
            onClicked: {
                fadeHighScoreHeader.start();
                fadeHighScores.start();
                fadeHighScoreFooter.start();
                isGameOver = false;
                hasHighScore = false;
                highScoreList.currentIndex = -1;
                mainview.startGame();
                timerResetView.start();
            }
        }
    } // highScoresFooter̈́

    // Timer to reset the view when rthe new game is started
    Timer {
        id: timerResetView
        interval: mainview.fadeOutDurationMs+50
        onTriggered: {
            highScoresHeader.opacity = 1;
            rectangleScores.opacity = 1;
            highScoresFooter.opacity = 1;
            back();
        }
    }

    // Animations
    PropertyAnimation { id: fadeHighScoreHeader; target: highScoresHeader; properties: "opacity"; to: 0; duration: mainview.fadeOutDurationMs }
    PropertyAnimation { id: fadeHighScores; target: rectangleScores; properties: "opacity"; to: 0; duration: mainview.fadeOutDurationMs }
    PropertyAnimation { id: fadeHighScoreFooter; target: highScoresFooter; properties: "opacity"; to: 0; duration: mainview.fadeOutDurationMs }
}

